package learn.servlet;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @USER white
 * @DATETIME 2020/12/12 17:14
 */
public class ServletTest extends HttpServlet {

    public static void main(String[] args) throws LifecycleException {
        //内置tomcat
        Tomcat tomcat = new Tomcat();
        tomcat.start();
        Connector connector = tomcat.getConnector();
        connector.setPort(8080);
        connector.setURIEncoding("utf8");

        Host host = tomcat.getHost();
        host.setAppBase("/deployPath部署路径");

        // 获取目录绝对路径
        String classPath = System.getProperty("user.dir");

        // 配置tomcat上下文
        Context context = tomcat.addContext(host, "contextPath根路径", classPath);

        // servlet
        Wrapper wrapper = tomcat.addServlet("/relativeRoot", "Servlet", new DispatcherServlet());
        wrapper.addMapping("url");

        tomcat.start();
        tomcat.getServer().await();

    }


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //存放异步所需的参数
        AsyncContext asyncContext = req.getAsyncContext();
        //存放servlet服务所需的参数
        ServletContext servletContext = req.getServletContext();
        //转发请求，传递
        asyncContext.dispatch("/anotherUrl");
//        asyncContext.addListener();

        //开启异步，其实只是创建上下文，并触发监听事件
        AsyncContext asyncContext1 = req.startAsync();
        //异步处理事务

        asyncContext.complete();
        super.service(req, resp);
    }
}
